<?php

namespace dk\core;


use Jresponse;

class Router{
    const DEF_TASK = 'index';
    const DEF_ACTION = 'index';
    const ACTION_NAME = '_a';

    protected $host = '';
    protected static $instance;

    protected function __construct(){
    }

    /**
     * @param mixed $host
     */
    public function setHost($host) {
        $this->host = $host;
    }

    /**
     * @return Router
     */
    public static function getInstance() {
        if (!isset(static::$instance)) {
            self::$instance = new self();
        }
        return static::$instance;
    }

    public function actionKey(){
        return self::ACTION_NAME;
    }

    public function getDefalutAction(){
        return self::DEF_ACTION;
    }

    public function getDefalutTask(){
        return self::DEF_TASK;
    }

    protected $forceAction;
    public function setForceAction($action){
        $this->forceAction = $action;
    }
    public function getForceAction(){
        return $this->forceAction;
    }

    public function getTask($part = ''){
        $task = Jrequest::getString($this->actionKey());
        if(!$task){
            $task = $this->getDefalutTask();
        }

        if(!preg_match('/^[\-a-z0-9A-Z]+$/', $task)){
            JResponse::http404();
        }
        
        if($part){
            $tmp = explode('-', $task);
            switch ($part) {
                case 'action':
                    return $tmp[0];
                case 'do':
                    return gav($tmp, 1, 'index');
            }
        }

        return $task;
    }

    function build($action, $params = []){
        if(is_numeric($params)){
            $params = array('id' => $params);
        }

        if(is_string($params)){
            parse_str($params, $params);
        }

        if(isset($params['_filter'])){
            if(is_string($params['_filter'])){
                $params['_filter'] = explode(',', $params['_filter']);
            }

            if($params['_filter'] && is_array($params['_filter'])){
                foreach ($params['_filter'] as $filter) {
                    unset($params[$filter]);
                }
            }

            unset($params['_filter']);
        }

        $action = preg_replace('/\.' . self::DEF_ACTION . '$/', '', $action);
        unset($params[self::ACTION_NAME]);

        ksort($params);
        $params = array_filter($params);
        $params = $params ? '&' . http_build_query($params) : '';
        $url = 'index.php?' . self::ACTION_NAME . '=' . str_replace('.', '-', $action) . $params;
        /*$url = $this->host;
        $url = $url . '/index.php?' . self::ACTION_NAME . '=' . str_replace('.', '-', $action) . $params;*/
        $url = preg_replace('/\s/u', '%20', $url);

        return $url;
    }
}